import jsCookie from 'js-cookie'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Home from '../view/home/index.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    meta: { title: '首页' },
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        name: 'welcome',
        component: () => import('../view/home/welcome/index.vue'),
        meta: { title: '欢迎界面' }
      },
      {
        path: '/userlist',
        name: 'userlist',
        component: () => import('../view/user/userlist.vue'),
        meta: { title: '用户列表' }
      },
      {
        path: '/rolelist',
        name: 'rolelist',
        component: () => import('../view/role/rolelist.vue'),
        meta: { title: '角色列表' }
      },
      {
        path: '/authority',
        name: 'authority',
        component: () => import('../view/authority/authority.vue'),
        meta: { title: '权限列表' }
      },
      {
        path: '/articlelist',
        name: 'articlelist',
        component: () => import('../view/article/articlelist.vue'),
        meta: { title: '文章列表' }
      },
      {
        path: '/articleAdd',
        name: 'articleAdd',
        component: () => import('../view/article/articleAdd.vue'),
        meta: { title: '新增文章' }
      },
      {
        path: '/orderList',
        name: 'orderList',
        component: () => import('../view/order/orderList.vue'),
        meta: { title: '订单列表' }
      },
      {
        path: '/goodsList',
        name: 'goodsList',
        component: () => import('../view/goods/goodsList.vue'),
        meta: { title: '商品列表' }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../view/login/index.vue')
  },
  {
    path: '/:pathMatch(.*)',
    component: () => import('../view/notFond/idnex.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to: any, from, next) => {
  const isToken = jsCookie.get('token')
  if (to.path === '/login') {
    if (isToken) next('/home')
    else next()
  } else {
    if (!isToken) {
      next('/login')
    } else {
      next()
    }
  }

  // 设置标题
  window.document.title = to.meta.title || ''
})

export default router
